package com.study.ming.studydemo.thd;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.*;

/**
 * CountDownLatch同步计数器，当计数器数值减为0时，所有受其影响而等待的线程将会被激活
 */
public class CountDownLatchDemo {

    private static final CountDownLatch lock = new CountDownLatch(5);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            new Thread("t" + i) {
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":到达");
                        ThreadLocalRandom.current().nextInt(5);
                        TimeUnit.SECONDS.sleep(4);
                        System.out.println(Thread.currentThread().getName() + ":放行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.countDown();
                    }
                }
            }.start();
//            TimeUnit.SECONDS.sleep(1);
        }
        TimeUnit.SECONDS.sleep(1);
        lock.await();
        System.out.println("111");
    }

    @Test
    public void wqerqwer() {
        ExecutorService service = Executors.newCachedThreadPool();
        final CountDownLatch caipan = new CountDownLatch(1);
        final CountDownLatch cdAnswer = new CountDownLatch(4);
        for (int i = 0; i < 4; i++) {
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        System.out.println("选手" + Thread.currentThread().getName() + "正等待裁判发布口令");
                        caipan.await();
                        System.out.println("选手" + Thread.currentThread().getName() + "开始奔跑...");
                        final Random r = new Random();
                        final int a = r.nextInt(9) + 1;
                        TimeUnit.SECONDS.sleep(a);
                        System.out.println("选手" + Thread.currentThread().getName() + "到达终点, 耗时" + a + "分钟");
                        cdAnswer.countDown();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }
        try {
            for (int i = 3; i >= 0; i--) {
                Thread.sleep(1000);
                System.out.println(i);
            }
            caipan.countDown();
            cdAnswer.await();
            System.out.println("所有选手都到达终点");
            System.out.println("裁判" + Thread.currentThread().getName() + "汇总成绩排名");
        } catch (Exception e) {
            e.printStackTrace();
        }
        service.shutdown();
    }

    @Test
    public void dfasdf() {
        final int i = ThreadLocalRandom.current().nextInt(5);
        System.out.println(i);
    }
}
